package com.yaopaikeji.controller;

import com.github.pagehelper.PageInfo;
import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.constants.RestResult;
import com.yaopaikeji.constants.ResultsEnum;
import com.yaopaikeji.interceptor.Auth;
import com.yaopaikeji.model.ContactUsInfo;
import com.yaopaikeji.service.ContactUsService;
import com.yaopaikeji.service.UserService;
import com.yaopaikeji.service.impl.MailSendService;
import com.yaopaikeji.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/contact-us")
public class ContractUsController {

    @Autowired
    private ContactUsService contactUsService;

    @Autowired
    private UserService userService;

    @Autowired
    private MailSendService mailSendService;

    @PostMapping("/submit")
    public RestResult<String> submitContactUs(@RequestBody ContactUsInfo contactUsInfo) {

        contactUsInfo.setStatus(Constants.NOT_READ);
        contactUsInfo.setCreateTime(TimeUtil.now());

        boolean isSuccess = contactUsService.saveContractUs(contactUsInfo);

        if(!isSuccess)
            return new RestResult<>(ResultsEnum.SYS_ERROR);

        //TODO:邮件列表
        mailSendService.sendContactUsMail(contactUsInfo, Arrays.asList("xianhou.meng@yaopaikeji.com"));

        return new RestResult<>(ResultsEnum.SUCCESS);
    }

    @Auth
    @GetMapping("/info/listAll")
    public RestResult<List<ContactUsInfo>> listAllContactUsInfos(){

        return new RestResult<>(contactUsService.listContactUsInfoAll());
    }

    @Auth
    @GetMapping("/info/mark-read/{id}")
    public RestResult markRead(@PathVariable("id") Integer infoId){

        return new RestResult<>(contactUsService.updateContactUsStatusToRead(infoId,userService.getCurrentUser()));
    }

    @Auth
    @GetMapping("/info/{id}")
    public RestResult<ContactUsInfo> getContactUsInfoById(@PathVariable("id")Integer id){

        return new RestResult<>(contactUsService.getContactUsInfoById(id));
    }

    @Auth
    @GetMapping("/info/page/{currentPage}")
    public RestResult<PageInfo<ContactUsInfo>> getContactUsInfosByPage(@PathVariable("currentPage") Integer currentPage){

        return new RestResult<>(contactUsService.listByPage(currentPage,Constants.PAGE_SIZE));
    }
}
